﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.Contract.ContractSrm;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.BcrReadInfos;
using HamcoWcs.Entitys.Logs;
using HamcoWcs.Entitys.MainTaskBaks;
using HamcoWcs.Entitys.MainTasks;
using HamcoWcs.Models.Charts;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Exceptions;
using HamcoWcs.Models.ForeEndModels.Basic;
using HamcoWcs.Models.ForeEndModels.BI;
using HamcoWcs.Service.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace HamcoWcs.Main.Controllers.Chart
{
    /// <summary>
    /// 报表数据接口
    /// </summary>
    public class ChartController : BasicController
    {

        private readonly ILocationService _locationService;
        private readonly IBaseSrmTaskService _baseSrmTaskService;
        private readonly IPconBaseService _pconBaseService;
        private readonly AutomaticStorageInfo _asrs;
        /// <summary>
        /// 
        /// </summary>
        public override string ControllerName => "ChartController";

        /// <summary>
        /// 构造函数
        /// </summary>
        public ChartController(AutomaticStorageInfo asrs, WcsDbContext wcsDbContext, IMapper mapper, ILoggerService loggerService, ILocationService locationService,
            IBaseSrmTaskService baseSrmTaskService, IPconBaseService pconBaseService)
            : base(loggerService, mapper, wcsDbContext)
        {
            _locationService = locationService;
            _baseSrmTaskService = baseSrmTaskService;
            _pconBaseService = pconBaseService;
            _asrs = asrs;
        }



        /// <summary>获取内存使用率和磁盘使用率</summary>
        [HttpPost]
        public async Task<IActionResult> GetChartData()
        {
            try
            {
                var menoryUseRate = await ComputerHelper.GetMemoryUsedRateAsync();
                var driveUseRate = await ComputerHelper.GetDriverUsedRateAsync();
                //var zones = _locationService.InventoryZones();
                //ShelfChartDto shelfData = new ShelfChartDto(zones);

                var chartDto = new ChartDto()
                {
                    MemoryUseRate = menoryUseRate,
                    DriveUseRate = driveUseRate,
                    //ShelfData = shelfData
                };

                return Json(new ForeEndResult(chartDto));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
                //_loggerService.AddSystemErrorLog("ChartController->GetChatData:" + ex.Message);
                //return Json(ForeEndResult.Fail("生成报表数据失败"));
            }
        }


        /// <summary>获取货架数据</summary>
        [HttpPost]
        public IActionResult GetShelfChartData()
        {
            try
            {
                var zones = _locationService.InventoryZones();

                var shelfData = new ShelfChartDto(zones);
                var chartDto = new ChartDto()
                {
                    ShelfData = shelfData
                };
                return Json(new ForeEndResult(chartDto));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();

                //_loggerService.AddSystemErrorLog("ChartController->GetShelfChartData:" + ex.Message);
                //return Json(ForeEndResult.Fail("生成报表数据失败"));
            }
        }

        /// <summary>
        /// 每月入库数量，出库数量，以及任务总数 折线图
        /// </summary>
        /// <param name="taskAmount"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult LineWeekTask()
        {
            try
            {
                //Thread.Sleep(11000);

                var now = DateTime.Now.Date;
                var startDate = now.AddDays(-30);
                var tasks = _wcsDbContext.MainTaskBaks
                    .Where(x => x.TaskStatus != "Cancel")
                    .Where(x => x.CompleteTime >= startDate)
                    .ToList();


                //var amounts = _wcsDbContext.TaskAmounts.Where(x => x.CreatedTime.AddDays(30) >= now).ToList();
                var chart = new LineChartModel { Title = "任务变化率" };




                var wharfin = new ChartDataItem() { Name = "码头入库" };
                var wharfout = new ChartDataItem() { Name = "码头出库" };
                var productin = new ChartDataItem() { Name = "成品入库" };
                var tomfc = new ChartDataItem() { Name = "成品入" };
                var moveData = new ChartDataItem() { Name = "倒库" };
                var totalData = new ChartDataItem() { Name = "总数" };
                chart.Series.Add(wharfin);
                chart.Series.Add(wharfout);
                chart.Series.Add(productin);
                chart.Series.Add(tomfc);
                chart.Series.Add(moveData);
                chart.Series.Add(totalData);

                for (DateTime date = now.AddDays(-30); date < now; date = date.AddDays(1))
                {
                    chart.Titles.Add(date.ToString("M"));
                    var ttasks = tasks.Where(d => d.CompleteTime.Date == date);
                    wharfin.Values.Add(ttasks == null ? "0" : ttasks.Where(x => x.SrcMachine.Contains("CJRCV")).Count().ToString());
                    wharfout.Values.Add(ttasks == null ? "0" : ttasks.Where(x => x.DesMachine.Contains("CJRCV")).Count().ToString());
                    productin.Values.Add(ttasks == null ? "0" : ttasks.Where(x => x.SrcMachine.Contains("CJMCV")).Count().ToString());
                    tomfc.Values.Add(ttasks == null ? "0" : ttasks.Where(x => x.DesMachine.Contains("CJMCV")).Count().ToString());
                    moveData.Values.Add(ttasks == null ? "0" : ttasks.Where(x => x.SrcMachine.Contains("CJSTW") && x.DesMachine.Contains("CJSTW")).Count().ToString());
                    totalData.Values.Add(ttasks == null ? "0" : ttasks.Count().ToString());
                }

                chart.Legends = chart.Series.Select(d => d.Name).ToList();
                return Json(new UIDashboardResult(chart));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
                //return Json(ForeEndResult.Fail(e.Message));
            }
        }

        /// <summary>
        /// 当前入库数量，出库数量，等待入库数量，等待出库数量
        /// </summary>
        [HttpPost(nameof(CountNowTask))]
        public IActionResult CountNowTask()
        {
            try
            {
                var dic = new Dictionary<string, int>();
                var tasks = _wcsDbContext.MainTasks.ToList();
                dic.Add("总任务数", tasks.Count);
                dic.Add("入库任务数", tasks.Where(x => x.MainTaskType == EnumMainTaskType.InboundTask.ToString()).Count());
                dic.Add("出库任务数", tasks.Where(x => x.MainTaskType == EnumMainTaskType.OutboundTask.ToString()).Count());
                dic.Add("移库任务数", tasks.Where(x => x.MainTaskType == EnumMainTaskType.LocMoveTask.ToString()).Count());

                var chart = new ChartModelBase("当前任务汇总");
                chart.Titles = dic.Keys.ToList();
                chart.Values = dic.Values.Select(x => x.ToString()).ToList();
                return Json(new UIDashboardResult(chart));
            }
            catch (Exception e)
            {
                AddSystemLog(e.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 每周入库数量，出库数量，以及任务总数 柱状图
        /// </summary>
        [HttpPost]
        public IActionResult CountWeekTask()
        {
            try
            {
                DateTime nowdata = DateTime.Now;
                var amounts = _wcsDbContext.TaskAmounts.Where(x => x.CreatedTime.AddDays(7) >= nowdata).ToList();
                //当前运行的任务数量
                var taskAmount = new UITaskAmount();
                foreach (var count in amounts)
                {
                    taskAmount.TotalAmount += int.Parse(count.TotalTaskAmount);
                    taskAmount.InboundAmount += int.Parse(count.InboundTaskAmount);
                    taskAmount.OutboundAmount += int.Parse(count.OutboundTaskAmount);
                }

                var chart = taskAmount.ConvertChartsModel("每周任务汇总");
                return Json(new UIDashboardResult(chart));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }



        /// <summary>
        /// 每天入库数(取年月日)
        /// </summary>
        [HttpPost]
        public IActionResult DailyTaskQueryModel(DailyTaskQueryModel model)
        {
            try
            {
                var year = model.Date.Year;
                var month = model.Date.Month;
                var day = model.Date.Day;

                var starttime = new DateTime(year, month, day, 0, 0, 0);
                var endtime = new DateTime(year, month, day, 23, 59, 59);

                var tasks = _wcsDbContext.MainTaskBaks
                    .AsNoTracking()
                    .Where(x => x.CompleteTime >= starttime && x.CompleteTime <= endtime)
                    .Where(x => x.TaskStatus != "Cancel")
                    .ToList();

                var dic = new Dictionary<string, object>
                {
                    { "总清洗机", tasks.Where(x => x.DesMachine.Contains("CJMCV")).Count() },
                    { "总成品入库", tasks.Where(x => x.SrcMachine.Contains("CJMCV") && x.DesMachine.Contains("CJSTW")).Count() },
                    { "总码头入库", tasks.Where(x => x.SrcMachine.Contains("CJRCV") && x.DesMachine.Contains("CJSTW")).Count() },
                    { "总码头出库", tasks.Where(x => x.SrcMachine.Contains("CJSTW") && x.DesMachine.Contains("CJRCV")).Count() },
                    { "总倒库", tasks.Where(x => x.TaskId.Contains("-A") ||  x.TaskId.Contains("-B")).Count() },
                };

                for (int i = 0; i < 24; i++)
                {
                    var st = starttime.AddHours(i);
                    var et = starttime.AddHours(i + 1);
                    var ttasks = tasks.Where(x => x.CompleteTime >= st && x.CompleteTime < et).ToList();

                    dic.Add($"{st:HH:mm}-{et:HH:mm}", new Dictionary<string, int>
                    {
                        { "清洗机", ttasks.Where(x => x.DesMachine.Contains("CJMCV")).Count() },
                        { "成品入库", ttasks.Where(x => x.SrcMachine.Contains("CJMCV") && x.DesMachine.Contains("CJSTW")).Count() },
                        { "码头入库", ttasks.Where(x => x.SrcMachine.Contains("CJRCV") && x.DesMachine.Contains("CJSTW")).Count() },
                        { "码头出库", ttasks.Where(x => x.SrcMachine.Contains("CJSTW") && x.DesMachine.Contains("CJRCV")).Count() },
                        { "倒库", ttasks.Where(x => x.TaskId.Contains("-A") ||  x.TaskId.Contains("-B")).Count() },
                    });
                }


                return Json(dic);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 按时间段检索任务数量
        /// </summary>
        [HttpPost]
        public IActionResult RangeTaskQuery(RangeTaskQueryModel model)
        {
            try
            {

                if (model.StartTime > model.EndTime)
                    throw new WarningException("选择的时间异常");

                var tasks = _wcsDbContext.MainTaskBaks
                    .AsNoTracking()
                    .Where(x => x.CompleteTime >= model.StartTime && x.CompleteTime <= model.EndTime)
                    .Where(x => x.TaskStatus != "Cancel")
                    .ToList();

                var dic = new Dictionary<string, object>
                {
                    { "清洗机", tasks.Where(x => x.DesMachine.Contains("CJMCV")).Count() },
                    { "成品入库", tasks.Where(x => x.SrcMachine.Contains("CJMCV") && x.DesMachine.Contains("CJSTW")).Count() },
                    { "码头入库", tasks.Where(x => x.SrcMachine.Contains("CJRCV") && x.DesMachine.Contains("CJSTW")).Count() },
                    { "码头出库", tasks.Where(x => x.SrcMachine.Contains("CJSTW") && x.DesMachine.Contains("CJRCV")).Count() },
                    { "倒库", tasks.Where(x => x.TaskId.Contains("-A") ||  x.TaskId.Contains("-B")).Count() },
                };
                return Json(new ForeEndResult(dic));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 昨日产能
        /// </summary>
        [HttpGet, HttpPost]
        public IActionResult YesterdayCapacity()
        {
            try
            {
                var y = DateTime.Now.AddDays(-1);

                var starttime = new DateTime(y.Year, y.Month, y.Day, 0, 0, 0);
                var endtime = new DateTime(y.Year, y.Month, y.Day, 23, 59, 59);

                var tasks = _wcsDbContext.MainTaskBaks
                    .AsNoTracking()
                    .Where(x => x.CompleteTime >= starttime && x.CompleteTime <= endtime)
                    .Where(x => x.TaskStatus != "Cancel")
                    .ToList();


                var dic = new Dictionary<string, object>
                {
                    { "清洗机", tasks.Where(x => x.DesMachine.Contains("CJMCV")).Count() },
                    { "成品入库", tasks.Where(x => x.SrcMachine.Contains("CJMCV") && x.DesMachine.Contains("CJSTW")).Count() },
                    { "码头入库", tasks.Where(x => x.SrcMachine.Contains("CJRCV") && x.DesMachine.Contains("CJSTW")).Count() },
                    { "码头出库", tasks.Where(x => x.SrcMachine.Contains("CJSTW") && x.DesMachine.Contains("CJRCV")).Count() },
                    { "倒库", tasks.Where(x => x.TaskId.Contains("-A") ||  x.TaskId.Contains("-B")).Count() },
                };

                var data = new Dictionary<string, object>()
                {
                      { "title", "昨日产能" },
                      { "data", dic },
                };
                return Json(new ForeEndResult(data));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }



        /// <summary>
        /// 设备统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ChartEquipment()
        {
            return Ok();
            throw new NotImplementedException();
            //try
            //{
            //    var uIEquipment = new UIEquipment();
            //    var srms = _baseSrmTaskService.GetAllSrmPlcs();//foreach一次
            //    foreach (var srm in srms)
            //    {
            //        switch (srm.DeviceMode)
            //        {
            //            case 1: uIEquipment.Starting++; break;
            //            case 4: uIEquipment.Error++; break;
            //            default: uIEquipment.Other++; break;
            //        }
            //    }
            //    var pcons = _pconBaseService.GetAllPconPlcs();//套两次 plc pcon
            //    foreach (var pconPlcs in pcons)
            //    {
            //        foreach (var pcon in pconPlcs.Pcons.Values)
            //        {
            //            //uIEquipment.Toal++;
            //            switch (pcon.PconMode)
            //            {
            //                case 1: uIEquipment.Starting++; break;
            //                case 4: uIEquipment.Error++; break;
            //                default: uIEquipment.Other++; break;
            //            }
            //        }
            //    }
            //    //uIEquipment.Toal += srms.Count();
            //    var chart = uIEquipment.ConvertPieChartsModel("设备状态图");
            //    return Json(new UIDashboardResult(chart));
            //    //return Json(new UIDashboardResult(uIEquipment));
            //}
            //catch (Exception e)
            //{
            //    return Json(ForeEndResult.Fail(e.Message));
            //}
        }


        /// <summary>
        /// 获取读码率By Hour
        /// </summary>
        [HttpPost]
        public IActionResult GetBcrRateByHour(DailyTaskQueryModel model)
        {
            if (model == null) { model = new DailyTaskQueryModel() { Date = DateTime.Now }; }
            try
            {
                //var tDate = model.Date.Date;
                var dStr = model.Date.ToString("yyyy年MM月dd日");
                var dic = new Dictionary<string, object>()
                {
                    {"Title", $"{dStr} Bcr读取率统计" },
                    {"Date",dStr },
                };

                var datas = _wcsDbContext.Set<BcrReadInfo>()
                    .AsNoTracking()
                    .Where(x => x.SetTime.Date == model.Date.Date && x.SetTime.Hour == model.Date.Hour)
                    .ToList();

                ;
                dic.Add("Data", datas.Select(x => new BcrRate(x.BcrName, x.RQty, x.FQty)));


                return Json(new ForeEndResult(dic));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


        /// <summary>
        /// 获取读码率By Day
        /// </summary>
        [HttpPost]
        public IActionResult GetBcrRateByDay(DailyTaskQueryModel model)
        {
            if (model == null) { model = new DailyTaskQueryModel() { Date = DateTime.Now }; }
            try
            {
                var tDate = model.Date.Date;
                var dStr = model.Date.ToString("yyyy年MM月dd日");
                var dic = new Dictionary<string, object>()
                {
                    {"Title", $"{dStr} Bcr读取率统计" },
                    {"Date",dStr },
                };


                var datas = _wcsDbContext.Set<BcrReadInfo>()
                    .AsNoTracking()
                    .Where(x => x.SetTime.Date == tDate)
                    .GroupBy(x => x.BcrName)
                    .Select(x => new BcrRate(x.Key, x.Sum(k => k.RQty), x.Sum(k => k.FQty)))
                    .ToList();

                dic.Add("Data", datas);
                //for (int i = 0; i < 24; i++)
                //{
                //    var currentTime = tDate.AddHours(i);
                //    var tDatas = datas
                //        .Where(x => x.SetTime == currentTime)
                //        .Select(x => new BcrRate(x.BcrName, x.RQty, x.FQty))
                //        .ToList();

                //    dic.Add(currentTime.ToString("HH:00"), tDatas);
                //}

                return Json(new ForeEndResult(dic));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 获取读码率By Month
        /// </summary>
        [HttpPost]
        public IActionResult GetBcrRateByMonth(DailyTaskQueryModel model)
        {
            if (model == null) { model = new DailyTaskQueryModel() { Date = DateTime.Now }; }

            try
            {
                var tDate = model.Date;
                var dStr = model.Date.ToString("yyyy年MM月");
                var dic = new Dictionary<string, object>()
                {
                    {"Title", $"{dStr} Bcr读取率统计" },
                    {"Date",dStr },
                };

                //var datas = _wcsDbContext.Set<BcrReadInfo>()
                //    .AsNoTracking()
                //    .Where(x => x.SetTime.Year == tDate.Year && x.SetTime.Month == tDate.Month)
                //    .ToList();

                var datas = _wcsDbContext.Set<BcrReadInfo>()
                    .AsNoTracking()
                    .Where(x => x.SetTime.Year == tDate.Year && x.SetTime.Month == tDate.Month)
                    .GroupBy(x => x.BcrName)
                    .Select(x => new BcrRate(x.Key, x.Sum(k => k.RQty), x.Sum(k => k.FQty)))
                    .ToList();
                //var sDate = new DateTime(tDate.Year, tDate.Month, 1);
                //var maxDate = sDate.AddMonths(1);
                //for (DateTime date = sDate; date < maxDate; date = date.AddDays(1))
                //{
                //    var tDatas = datas
                //        .Where(x => x.SetTime.Date == date)
                //        .Select(x => new BcrRate(x.BcrName, x.RQty, x.FQty))
                //        .ToList();

                //    dic.Add(date.ToString("dd"), tDatas);
                //}
                dic.Add("Data", datas);

                return Json(new ForeEndResult(dic));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 获取读码率By Day Range
        /// </summary>
        [HttpPost]
        public IActionResult GetBcrRateByDayRange(TimeZoneQueryModel model)
        {
            try
            {
                var dSStr = model.StartTime.ToString("yyyy年MM月dd日");
                var dEStr = model.EndTime.ToString("yyyy年MM月dd日");
                var dic = new Dictionary<string, object>()
                {
                    {"Title", $"{dSStr}-{dEStr} Bcr读取率统计" },
                    {"Date", $"{dSStr}-{dEStr}" },
                };


                var datas = _wcsDbContext.Set<BcrReadInfo>()
                    .AsNoTracking()
                    .Where(x => x.SetTime >= model.StartTime && x.SetTime <= model.EndTime)
                    .GroupBy(x => x.BcrName)
                    .Select(x => new BcrRate(x.Key, x.Sum(k => k.RQty), x.Sum(k => k.FQty)))
                    .ToList();

                dic.Add("Data", datas);

                return Json(new ForeEndResult(dic));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


        private static int _troubleThreshold = 12 * 60; // unit : s

        /// <summary>
        /// 获取设备运行统计报表（直接导出）
        /// </summary>
        [HttpPost]
        public IActionResult GetMachineRunReport(TimeZoneQueryModel model)
        {
            try
            {
                if (model is null)
                    throw new WarningException("传入的时间错误");

                var errordates = _wcsDbContext.DeviceErrorLogs
                    .AsNoTracking()
                    .Where(x => x.DeviceName.Contains("CJ"))
                    .Where(x => x.CreatedTime >= model.StartTime && x.LastUpdateTime <= model.EndTime)
                    .Where(x => !x.IsCsotError)
                    .ToList();

                //var g = new Dictionary<string, List<DeviceErrorLog>>();


                var g = errordates.OrderBy(x => x.DeviceName).GroupBy(x => x.DeviceName.Split('-').First()).ToList();

                var tasks = _wcsDbContext.MainTaskBaks
                    .AsNoTracking()
                    .Where(x => x.CreatedTime >= model.StartTime && x.LastUpdateTime <= model.EndTime)
                    .Where(x => x.TaskStatus == "Delete" && x.MainTaskType != "InventoryTask")
                    .Include(x => x.SubTasks)
                    .ToList();

                var taskCount = tasks.Count;

                var dic = new Dictionary<string, MachineRunModel>();

                //var g = errordates.GroupBy(x => x.DeviceName).ToList();
                var productTime = (model.EndTime - model.StartTime).TotalMinutes;

                foreach (var errordate in g)
                {
                    var machineName = errordate.Key;
                    var m = new MachineRunModel() { MachineName = machineName };

                    dic.Add(errordate.Key, m);
                    int cycleCount = GetCycleCount(tasks, machineName);
                    int troubleCount = errordate.Count(x => x.SetTime.GetSecond() > _troubleThreshold);
                    int maintainCount = errordate.Count() - troubleCount;


                    m.CycleCount = cycleCount;
                    m.ProductTime = productTime;
                    m.MaintainCount = maintainCount;
                    m.TrobuleCount = troubleCount;
                    m.MaintainTime = GetTotlaSecond(errordate.Where(x => x.SetTime.GetSecond() <= 12 * 60).Select(x => new TimeZoneQueryModel() { StartTime = x.CreatedTime, EndTime = x.LastUpdateTime }).ToList()) / 60;
                    m.TrobuleTime = GetTotlaSecond(errordate.Where(x => x.SetTime.GetSecond() > 12 * 60).Select(x => new TimeZoneQueryModel() { StartTime = x.CreatedTime, EndTime = x.LastUpdateTime }).ToList()) / 60;

                    m.Update();
                }

                var machines = _asrs.Nodes.Select(x => x.NodeName).ToList();

                foreach (var machine in machines)
                {
                    if (!dic.ContainsKey(machine))
                    {
                        var m = new MachineRunModel
                        {
                            MachineName = machine,
                            ProductTime = productTime,
                            CycleCount = GetCycleCount(tasks, machine)
                        };
                        m.Update();
                        dic.Add(machine, m);
                    }
                }

                return Json(new ForeEndResult(dic.Values));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


        private int GetCycleCount(List<MainTaskBak> tasks, string machineName)
        {
            int cycleCount = 0;

            if (machineName.Contains("CJRGV100"))
            {
                cycleCount = tasks.Where(x => x.SrcMachine.Contains("CJMCV") || x.DesMachine.Contains("CJMCV")).Count();
            }
            else if (machineName.Contains("CJRGV200"))
            {
                cycleCount = tasks.Where(x => (x.SrcMachine == "CJSTW200" && x.DesMachine.Contains("CJMCV"))
                || (x.SrcMachine.Contains("CJMCV") && x.DesMachine == "CJSTW200"))
                    .Count();
            }
            else if (machineName.Contains("CJSTW"))
            {
                cycleCount = tasks.Where(x => x.SrcMachine.Contains(machineName)
                || x.DesMachine.Contains(machineName)).Count();
            }
            else if (machineName.Contains("CJMCV"))
            {
                cycleCount = tasks.Count(x => x.DesMachine.Contains(machineName) || x.SrcMachine.Contains(machineName));
            }
            else
            {
                cycleCount = tasks.Count(x => x.SubTasks.Any(x => x.FromLoc == machineName || x.ToLoc == machineName));

            }

            return cycleCount;
        }

        private double GetTotlaSecond(IEnumerable<TimeZoneQueryModel> ts)
        {
            var list = new List<TimeZoneQueryModel>();

            foreach (var t in ts)
            {
                var i = list.FirstOrDefault(x => x.StartTime <= t.StartTime && x.EndTime <= t.EndTime && x.EndTime > t.StartTime);
                var j = list.FirstOrDefault(x => x.StartTime >= t.StartTime && x.EndTime >= t.EndTime && x.StartTime < t.EndTime);
                var k = list.FirstOrDefault(x => x.StartTime <= t.StartTime && x.EndTime >= t.EndTime);

                if (k == null)
                {
                    if (i != null && j != null)
                    {
                        list.Remove(i);
                        list.Remove(j);
                        list.Add(t);
                    }
                    else if (i != null)
                    {
                        i.EndTime = t.EndTime;
                    }
                    else if (j != null)
                    {
                        j.StartTime = t.StartTime;
                    }
                    else
                    {
                        list.Add(t);
                    }
                }
            }



            double totalSeconds = 0;

            foreach (var l in list)
            {
                totalSeconds += (l.EndTime - l.StartTime).TotalSeconds;
            }
            return totalSeconds;
        }

    }

    public class MachineRunModel
    {
        public void Update()
        {
            MCBF = TrobuleCount > 0 ? CycleCount / TrobuleCount : CycleCount;
            MCBA = MaintainCount > 0 ? CycleCount / MaintainCount : CycleCount;
            MTTR = MaintainCount > 0 ? MaintainTime / MaintainCount : MaintainTime;
            MTBF = TrobuleCount > 0 ? (ProductTime - TrobuleTime) / TrobuleCount : ProductTime;
            MTBA = MaintainCount > 0 ? (ProductTime - MaintainTime) / MaintainCount : ProductTime;
            UpTime = 1 - ((MaintainTime + TrobuleTime) / ProductTime);
        }

        /// <summary>
        /// 机台名
        /// </summary>
        public string MachineName { get; set; }
        /// <summary>
        /// 搬送次数
        /// </summary>
        public int CycleCount { get; set; }
        /// <summary>
        /// 维修次数
        /// </summary>
        public int MaintainCount { get; set; }
        /// <summary>
        /// 故障时间
        /// </summary>
        public int TrobuleCount { get; set; }
        /// <summary>
        /// 维修时间
        /// </summary>
        public double MaintainTime { get; set; }
        /// <summary>
        /// 故障时间
        /// </summary>
        public double TrobuleTime { get; set; }
        /// <summary>
        /// 生产时间
        /// </summary>
        public double ProductTime { get; set; }

        /// <summary>
        /// 平均故障周期(Cycle)
        /// </summary>
        public double MCBF { get; set; }
        /// <summary>
        /// 平均维修周期(Cycle)
        /// </summary>
        public double MCBA { get; set; }
        /// <summary>
        /// 平均维修时间
        /// </summary>
        public double MTTR { get; set; }
        /// <summary>
        /// 平均故障周期
        /// </summary>
        public double MTBF { get; set; }
        /// <summary>
        /// 平均维修周期
        /// </summary>
        public double MTBA { get; set; }
        /// <summary>
        /// 上线时间百分比
        /// </summary>
        public double UpTime { get; set; }


    }
}
